Page({
    data: {
        newsDetail: {} // 资讯详情
    },

    onLoad: function (options) {
        const newsId = options.id;
        if (newsId) {
            this.getNewsDetail(newsId);
        }
    },

    /**
     * 格式化日期时间
     */
    formatDateTime: function (timestamp) {
        // 判断时间戳是秒还是毫秒
        const time = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp;
        const date = new Date(time);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    /**
     * 获取资讯详情
     */
    getNewsDetail: function (newsId) {
        wx.showLoading({
            title: '加载中...'
        });
        wx.request({
            url: 'https://tea.qingnian8.com/xzs/news/detail',
            method: 'POST',
            header: {
                'access-key': 966432
            },
            data: {
                id: newsId
            },
            success: (res) => {
                console.log('资讯详情：', res.data);
                if (res.data.errCode === 0) {
                    const detail = res.data.data;
                    // 格式化日期
                    detail.publish_date = this.formatDateTime(detail.publish_date);
                    // 处理内容样式
                    if (detail.content) {
                        detail.content = detail.content
                            .replace(/<p>/g, '<p style="margin: 15px 0; line-height: 1.8;">')
                            .replace(/<img/g, '<img style="max-width: 100%; height: auto; display: block; margin: 20px 0;"');
                    }
                    this.setData({
                        newsDetail: detail
                    });
                } else {
                    wx.showToast({
                        title: res.data.errMsg || '获取失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('获取资讯详情失败：', err);
                wx.showToast({
                    title: '加载失败',
                    icon: 'none'
                });
            },
            complete: () => {
                wx.hideLoading();
            }
        });
    },

    /**
     * 分享文章
     */
    shareArticle: function () {
        wx.showToast({
            title: '分享功能',
            icon: 'none',
            duration: 2000
        });
    }
})

